package com.ruoyi.web.controller.pointRecord;

import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pointRecord.service.ILogisticsQueryService;
import com.ruoyi.pointRecord.service.IProductReturnService;
import com.ruoyi.pointRecord.dto.PointsExchangeRecordDTO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pointRecord.domain.PointsExchangeRecord;
import com.ruoyi.pointRecord.service.IPointsExchangeRecordService;
import com.ruoyi.pointRecord.service.IProductExchangeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 积分兑换记录Controller
 * 
 * @author amy
 * @date 2025-06-17
 */
@RestController
@RequestMapping("/pointRecord/pointRecord")
@Tag(name = "【积分兑换记录】管理")
@Slf4j
public class PointsExchangeRecordController extends BaseController
{
    @Autowired
    private IPointsExchangeRecordService pointsExchangeRecordService;

    @Autowired
    private IProductExchangeService productExchangeService;

    @Autowired
    private ILogisticsQueryService logisticsQueryService;

    @Autowired
    private IProductReturnService productReturnService;


    /**
     * 查询积分兑换记录列表
     */
    @Operation(summary = "查询积分兑换记录列表")
    @PreAuthorize("@ss.hasPermi('pointRecord:pointRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(PointsExchangeRecord pointsExchangeRecord)
    {
        startPage();
        List<PointsExchangeRecord> list = pointsExchangeRecordService.selectAllPointsExchangeRecordList(pointsExchangeRecord);
        return getDataTable(list);
    }

    /**
     * 查询用户积分兑换记录列表
     */
    @Operation(summary = "查询用户积分兑换记录列表")
    @GetMapping("/userList")
    public TableDataInfo userList(PointsExchangeRecord pointsExchangeRecord)
    {
        startPage();
        List<PointsExchangeRecord> list = pointsExchangeRecordService.selectUserPointsExchangeRecordList(pointsExchangeRecord);
        return getDataTable(list);
    }

    /**
     * 导出积分兑换记录列表
     */
    @Operation(summary = "导出积分兑换记录列表")
    @PreAuthorize("@ss.hasPermi('pointRecord:pointRecord:export')")
    @Log(title = "积分兑换记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PointsExchangeRecord pointsExchangeRecord)
    {
        List<PointsExchangeRecord> list = pointsExchangeRecordService.selectAllPointsExchangeRecordList(pointsExchangeRecord);
        ExcelUtil<PointsExchangeRecord> util = new ExcelUtil<PointsExchangeRecord>(PointsExchangeRecord.class);
        util.exportExcel(response, list, "积分兑换记录数据");
    }

    /**
     * 获取积分兑换记录详细信息
     */
    @Operation(summary = "获取积分兑换记录详细信息")
    @PreAuthorize("@ss.hasPermi('pointRecord:pointRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pointsExchangeRecordService.selectPointsExchangeRecordById(id));
    }

    /**
     * 新增积分兑换记录
     */
    @Operation(summary = "新增积分兑换记录")
    @Log(title = "积分兑换记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PointsExchangeRecord pointsExchangeRecord)
    {
        pointsExchangeRecord.setCreatedBy(getUsername());
        pointsExchangeRecord.setExchangeCode(CodeGeneratorUtil.generateCode());
        return toAjax(pointsExchangeRecordService.insertPointsExchangeRecord(pointsExchangeRecord));
    }

    /**
     * 修改积分兑换记录
     */
    @Operation(summary = "修改积分兑换记录")
    @PreAuthorize("@ss.hasPermi('pointRecord:pointRecord:edit')")
    @Log(title = "积分兑换记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PointsExchangeRecord pointsExchangeRecord)
    {
        pointsExchangeRecord.setUpdatedBy(getUsername());
        return toAjax(pointsExchangeRecordService.updatePointsExchangeRecord(pointsExchangeRecord));
    }

    /**
     * 删除积分兑换记录
     */
    @Operation(summary = "删除积分兑换记录")
    @PreAuthorize("@ss.hasPermi('pointRecord:pointRecord:remove')")
    @Log(title = "积分兑换记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable( name = "ids" ) Long[] ids) 
    {
        return toAjax(pointsExchangeRecordService.deletePointsExchangeRecordByIds(ids));
    }

    /**
     * 商品兑换
     */
    @Operation(summary = "商品兑换")
    @Log(title = "商品兑换", businessType = BusinessType.INSERT)
    @RateLimiter(time = 10, count = 3, key = "exchange", limitType = LimitType.IP)
    @PostMapping("/exchange")
    public AjaxResult exchangeProduct(@RequestBody PointsExchangeRecord pointsExchangeRecord)
    {
        return productExchangeService.exchangeProduct(pointsExchangeRecord);
    }

    /**
     * 查询物流信息
     */
    @Operation(summary = "查询物流信息")
    @GetMapping("/logistics/{id}")
    public AjaxResult queryLogistics(@PathVariable Long id) {
        try {
            PointsExchangeRecord record = pointsExchangeRecordService.selectPointsExchangeRecordById(id);

            if (record == null) {
                return AjaxResult.error("记录不存在");
            }

            // 检查权限 - 只能查看自己的记录
            if (!record.getUserId().equals(getUserId())) {
                return AjaxResult.error("无权限查看");
            }

            if (StringUtils.isBlank(record.getTrackingNumber())) {
                return AjaxResult.error("暂无物流单号");
            }

            Map<String, Object> logistics = logisticsQueryService.queryLogistics(record);
            return AjaxResult.success(logistics);

        } catch (Exception e) {
            log.error("查询物流失败：{}", e.getMessage());
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 直接查询物流信息 - 新增接口
     */
    @Operation(summary = "直接查询物流信息")
    @GetMapping("/logistics/direct")
    public AjaxResult directQueryLogistics(
            @RequestParam String trackingNumber,
            @RequestParam String logisticsCompany,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String fromAddress,
            @RequestParam(required = false) String toAddress) {
        try {
            Map<String, Object> logistics = logisticsQueryService.queryLogistics(
                    trackingNumber, logisticsCompany, phone, fromAddress, toAddress);
            return AjaxResult.success(logistics);

        } catch (Exception e) {
            log.error("直接查询物流失败：{}", e.getMessage());
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 批量查询用户物流信息
     */
    @Operation(summary = "用户物流列表")
    @GetMapping("/logistics/list")
    public TableDataInfo logisticsList(PointsExchangeRecord pointsExchangeRecord) {
        startPage();
        pointsExchangeRecord.setUserId(getUserId());

        List<PointsExchangeRecord> list = pointsExchangeRecordService.selectUserPointsExchangeRecordList(pointsExchangeRecord);

        // 为每个有物流单号的记录查询物流信息
        list.forEach(record -> {
            if (StringUtils.isNotBlank(record.getTrackingNumber()) &&
                    StringUtils.isNotBlank(record.getLogisticsCompany())) {
                try {
                    Map<String, Object> logistics = logisticsQueryService.queryLogistics(record);
                    record.getParams().put("logistics", logistics);
                } catch (Exception e) {
                    record.getParams().put("logisticsError", "查询失败: " + e.getMessage());
                }
            }
        });
        return getDataTable(list);
    }

    /**
     * 用户申请退货
     */
    @Operation(summary = "用户申请退货")
    @PostMapping("/apply")
    public AjaxResult applyReturn(@RequestBody PointsExchangeRecordDTO returnRequest) {
        return productReturnService.returnProduct(returnRequest);
    }

    /**
     * 用户取消兑换
     */
    @Operation(summary = "用户取消兑换")
    @PostMapping("/cancel")
    public AjaxResult cancelExchange(@RequestBody PointsExchangeRecord cancelRequest) {
        return productReturnService.cancelExchange(cancelRequest);
    }
}
